<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit2">
    <BasicForm @register="registerForm" ref="formRef">
      <template #productionSchedulingSchemeSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择排产方案" readonly
          @search="openPsAlwaysScheduling" />
      </template>
    </BasicForm>
    
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="排程订单内容" key="psPlanningSchedulingOrderContent" :forceRender="true">
        <vxe-toolbar>
          <template #buttons>
            来源类型：
            <a-select v-model:value="srcType" placeholder="请选择来源" @change="handleSrcTypeChanged" style="width: 140px">
              <a-select-option :value="1">MRP计划订单</a-select-option>
              <a-select-option :value="2">总装排产计划</a-select-option>
              <a-select-option :value="3">销售订单</a-select-option>
              <a-select-option :value="4">生产工单</a-select-option>
            </a-select>
            <a-button color="primary" style="margin-left:5px;" :disabled="isDetail"
              @click="masterPlanOpen()">新增</a-button>
          </template>
          <template #tools>
            
          </template>
        </vxe-toolbar>
        <JVxeTable keep-source resizable :rowNumber="true" rowNumKey="rowNum" ref="psPlanningSchedulingOrderContent"
          :loading="psPlanningSchedulingOrderContentTable.loading"
          :columns="psPlanningSchedulingOrderContentTable.columns"
          :dataSource="psPlanningSchedulingOrderContentTable.dataSource" :height="340">
          <template #srcDocTypeSlot="props">
            {{ props.row.srcDocType == 3 ? '销售订单' : props.row.srcDocType == 1 ? 'MRP计划订单' : props.row.srcDocType == 2?'总装排产计划' : '生产工单' }}
          </template>
          <template #action="props">
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props.row)">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 方案选择 -->
  <psAlwaysSchedulingSelectModel @register="psAlwaysSchedulingRegModal" @getSelectResult="psAlwaysSchedulinghandleSuccess"
    v-bind="getBindValue"></psAlwaysSchedulingSelectModel>
  <!-- 订单选择 -->
  <!-- <planOrerResultSelectModel @register="planOrderResultRegModal" @getSelectResult="planOrderResultHandleSuccess" v-bind="getBindValue" /> -->
  <!-- MPS生产主计划列表 -->
  <mpsSelectModel @register="mpsItemRegModal" @getSelectResult="mpsItemhandleSuccess" :multiple="true"
    v-bind="getBindValue" />
  <!-- 订单选择 -->
  <orderSelectModel @register="orderRegModal" @getSelectResult="orderhandleSuccess" :multiple="true"
    v-bind="getBindValue" />
  <!-- MRP计算结果 -->
  <productOrderSelectModal @register="registerProductOrderModal" @getSelectResult="productOrderhandleSuccess" :multiple="true" />
  <mrpResultModal @register="registerMrpResultModal" @getSelectResult="mrpResulthandleSuccess" :multiple="true" />
  <!-- 选择总装排产计划 -->
  <arrangementPlansSelectModel @register="arrangementPlanRegModal" @getSelectResult="arrangementPlanhandleSuccess"
    :multiple="true" v-bind="getBindValue" />
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods';
import { formSchema, psPrePlanningSchedulingOrderContentColumns, psPlanningSchedulingAvailableResourcesColumns } from '../PsPlanningScheduling.data';
import { saveOrUpdate, psPlanningSchedulingOrderContentList, psPlanningSchedulingAvailableResourcesList, distributePlan, getMpsItemByMainIds, getArrangementItemByMainIds } from '../PsPlanningScheduling.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import psAlwaysSchedulingSelectModel from '/@/views/components/psAlwaysSchedulingSelectModel.vue';
import orderSelectModel from '/@/views/components/orderSelectModel.vue';
// import planOrerResultSelectModel from '/@/views/components/planOrderResultSelectModel.vue';
import { useMessage } from '/@/hooks/web/useMessage';
import mpsSelectModel from '/@/views/components/mpsSelectModel.vue';
import arrangementPlansSelectModel from '/@/views/components/arrangementPlansSelectModel.vue';
import mrpResultModal from '/@/views/components/mrpResultModal.vue';
import productOrderSelectModal from '/@/views/components/productOrderSelectModal.vue';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref<boolean>(false)
const formDisabled = ref(false);
const refKeys = ref(['psPlanningSchedulingOrderContent']);
const activeKey = ref('psPlanningSchedulingOrderContent');
const psPlanningSchedulingOrderContent = ref();
const tableRefs = { psPlanningSchedulingOrderContent };
interface Props {
  planId: number | string
}
const srcType = ref<number>(1)
const operatFormItem = ref<any>(null)
const propsData = defineProps<Props>()
const psPlanningSchedulingOrderContentTable = reactive({
  loading: false,
  dataSource: <Array<any>>[],
  columns: psPrePlanningSchedulingOrderContentColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, getFieldsValue }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
const $message = useMessage();
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(requestAddOrEdit, classifyIntoFormData, tableRefs, activeKey, refKeys);

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail
  formDisabled.value = !data?.showFooter;

  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(psPlanningSchedulingOrderContentList, { id: data?.record?.id }, psPlanningSchedulingOrderContentTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});

//设置标题
const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'psPlanningSchedulingOrderContent';
  psPlanningSchedulingOrderContentTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    psPrePlanningSchedulingOrderContentList: allValues.tablesValue[0].tableData,
  };
}
function handleSrcTypeChanged(srcType) {
  console.log('srcType' + srcType)
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    if (values.relatedDemand) values.relatedDemand = 1;
    else values.relatedDemand = 0;
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const [psAlwaysSchedulingRegModal, { openModal: openpsAlwaysSchedulingModal }] = useModal();
// const [planOrderResultRegModal, { openModal: openPlanOrderResultModal }] = useModal();
const [mpsItemRegModal, { openModal: openMpsListModal }] = useModal();
const [orderRegModal, { openModal: openOrderListModal }] = useModal();
const [arrangementPlanRegModal, { openModal: openArrangementPlanModal }] = useModal();
const [registerMrpResultModal, { openModal: openMrpResultModal }] = useModal();
const [registerProductOrderModal, { openModal: openProductOrderModal }] = useModal();

const getBindValue = Object.assign({}, '');

function openPsAlwaysScheduling() {
  openpsAlwaysSchedulingModal(true, {
    isUpdate: false,
    showFooter: true,
    type: 1
  });
}
function masterPlanOpen() {
  switch (srcType.value) {
    case 1:
      openMrpResultModal(true, {
        isUpdate: true,
        showFooter: false,
      });
      break;
    case 2:
      openOrderListModal(true, {
        isUpdate: false,
        showFooter: true,
      });
      break;
    case 4:
      openProductOrderModal(true, {
        isUpdate: false,
        showFooter: true,
      });
      break;
    default:
      $message.createMessage.warn('请先选择计划方法');
      break;
  }
}

// mps筛选回写
function mpsItemhandleSuccess(val, values) {

}
// 获取Mps详情
async function getMpsDetail(ids) {
  let res = await getMpsItemByMainIds({
    ids: ids,
  });
  res.map((item) => {
    item.orderRowNum = item.rowNum;
    item.orderCenterId = item.id;
    delete item.id;
  });

  psPlanningSchedulingOrderContentTable.dataSource = res;
}
// mrp运算结果筛选
function mrpResulthandleSuccess(val, _value) {
  const contents = psPlanningSchedulingOrderContent.value!.getTableData();
  for (let i = 0; i < val.length; i++) {
    const v = val[i];
    const matchs = contents.filter(x => x.srcDocId == v.item.id)
    if (matchs && matchs.length > 0) continue;
    contents.push({
      srcDocType: srcType.value,
      srcDocNo: v.item.srcBillCode+'-'+v.item.rowNum,
      srcDocId: v.item.id,
      orderNo: v.item.orderBillCode,
      orderRowNo: v.item.orderRowNumber,
      srcDocLineNo: v.item.rowNum,
      productCode: v.item.materialCode,
      productName: v.item.materialName,
      orderDeliveryDate: v.item.demandDate,
      orderQuantity: v.item.orderQuantity,
      lastEndDischarge: '',
      totalProduction: v.item.adjustedMrpQuantity,
      actualProductionScheduling: ''
    })
  }
  psPlanningSchedulingOrderContentTable.dataSource = contents
}
// mrp运算结果筛选
function productOrderhandleSuccess(val, _value) {
  const contents = psPlanningSchedulingOrderContent.value!.getTableData();
  for (let i = 0; i < val.length; i++) {
    const v = val[i];
    const matchs = contents.filter(x => x.srcDocId == v.item.id)
    if (matchs && matchs.length > 0) continue;
    contents.push({
      srcDocType: srcType.value,
      srcDocNo: v.item.billCode,
      srcDocId: v.item.id,
      orderNo: v.item.orderBillCode,
      orderRowNo: v.item.orderRowNumber,
      srcDocLineNo: 10,
      productCode: v.item.materialCode,
      productName: v.item.materialName,
      orderDeliveryDate: v.item.planStartDate,
      orderQuantity: v.item.productQuantity,
      lastEndDischarge: '',
      totalProduction: v.item.productQuantity,
      actualProductionScheduling: ''
    })
  }
  psPlanningSchedulingOrderContentTable.dataSource = contents
}
// 总装排产计划回写
function arrangementPlanhandleSuccess(val, values, type) {

}
// 获取总装排产详情
async function getArrangementDetail(ids) {

}
//订单回写
function orderhandleSuccess(val, _values, _type) {
  psPlanningSchedulingOrderContentTable.dataSource = psPlanningSchedulingOrderContent.value!.getTableData();

  for (let i = 0; i < val.length; i++) {
    const v = val[i];

    const matchs = psPlanningSchedulingOrderContentTable.dataSource.filter(x => x.srcDocId == v.item.id)
    if (matchs && matchs.length > 0) continue;

    psPlanningSchedulingOrderContentTable.dataSource.push({
      mrpResultCode: '',
      srcDocType: srcType.value,
      srcDocId: v.item.id,
      srcDocNo: v.item.billCode,
      orderNo: v.item.billCode,
      orderRowNo: v.item.rowNum,
      srcDocLineNo: v.item.rowNum,
      productCode: v.item.materialCode,
      productName: v.item.materialName,
      orderDeliveryDate: v.item.orderDeliveryDate,
      orderQuantity: v.item.orderQuantity,
      lastEndDischarge: '',
      totalProduction: '',
      actualProductionScheduling: v.item.productQuantity,
    })
  }

}

function handleDelete(row: any) {
  psPlanningSchedulingOrderContentTable.dataSource = psPlanningSchedulingOrderContent.value!.getTableData();
  const index = psPlanningSchedulingOrderContentTable.dataSource.findIndex(x => x.srcDocId == row.srcDocId)
  psPlanningSchedulingOrderContentTable.dataSource.splice(index, 1)
}

function handleSubmit2() {
  handleSubmit()
}

function psAlwaysSchedulinghandleSuccess(val) {
  setFieldsValue({
    productionSchedulingScheme: val[0].label,
    productionSchedulingSchemeId: val[0].value,
  });
}
// 下发计划
const clickDistributePlan = async () => {
  await distributePlan({ id: propsData.planId })
  //关闭弹窗
  closeModal();
  //刷新列表
  emit('success');
}
// 模拟排产
const clickSimulatedScheduling = async () => {
  let data = getFieldsValue();
  await getSimulatedScheduling({ id: data.id.toString() })
  //关闭弹窗
  closeModal();
  //刷新列表
  emit('success');
}

</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>
